package model.fshare.client;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;

import model.fshare.Interface.FileTransmistObserver;
import model.infocenter.ClientUserInformations;


public class FileDownloading implements Runnable
{
	Socket dataSource;
	File fileToSave;
	FileTransmistObserver observer;
	
	public FileDownloading( File file, Socket socket, FileTransmistObserver observer )
	{
		fileToSave = file;
		dataSource = socket;
		this.observer = observer;
	}
	
	@Override
	public void run() 
	{
		try 
		{
			System.out.println( "====== FileDownloading: File Downloading Started! ======" );
			
			fileToSave.getParentFile().mkdirs();
			fileToSave.createNewFile();
			
			DataOutputStream fileWriter = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( fileToSave ) ) );

			DataInputStream dataReader = new DataInputStream( new BufferedInputStream( dataSource.getInputStream() ) );
			
			byte[] buf = new byte[1024*10];
			int bytesReaded = 0;
			ClientUserInformations clientUser = ClientUserInformations.getInstance();
			while( (bytesReaded = dataReader.read(buf)) != -1 )
			{
				if ( clientUser.getCurRoomId() == -1 )
				{
					fileWriter.close();
					dataSource.close();
					if ( fileToSave.exists() )
					{
						fileToSave.delete();
					}
					
					return;
				}
				
				fileWriter.write( buf, 0, bytesReaded );
				fileWriter.flush();
			}
			
			fileWriter.close();
			dataSource.close();

			observer.update();
			System.out.println( "====== FileDownloading: File Downloading Complished! ======" );
		}
		catch ( Exception e ) 
		{
			// When exception happended,
			// delete the imcomplete local file.
			if ( fileToSave.exists() )
			{
				fileToSave.delete();
			}
			observer.failed();
			
			e.printStackTrace();
		}
		
	}

}
